import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_house_manager/api/user.dart';
import 'package:flutter_house_manager/utils/Emitter.dart';
import 'package:flutter_house_manager/utils/TokenManager.dart';
import 'package:flutter_house_manager/utils/toast.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key, this.toName});
  final String? toName;
  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  int seconds = 60;
  Timer? timer;
  bool isSendCode = false; //是否发送了验证码 只能发一个
  //开始倒计时的方法
  void beginCount() async {
    //如果发送了验证码 就不能再发送了
    if (isSendCode) {
      PromptAction.showToast('正在发送$seconds秒后再发送');
      return;
    }
    //检验手机号是否为空
    if (phoneController.text.isEmpty) {
      PromptAction.showToast('请输入手机号');
      return;
    }
    //检验手机号是否满足规范
    if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(phoneController.text)) {
      PromptAction.showToast('请输入正确的手机号');
      return;
    }
    //可以发送验证码了
    isSendCode = true;
    final res = await sendCodeAPI({
      "mobile": phoneController.text,
    });
    PromptAction.showToast(res.toString());
    Timer.periodic(const Duration(seconds: 2), (timer) {
      codeController.text = res['code'];
    });

    PromptAction.showToast('验证码已发送');
    if (seconds == 60) {
      //才可以倒计时
      Timer.periodic(const Duration(seconds: 1), (timer) {
        if (seconds == 0) {
          timer.cancel();
          seconds = 60;
          isSendCode = false;

          setState(() {});
          return;
        }
        seconds--;
        setState(() {});
      });
    } else {
      PromptAction.showToast('请$seconds秒后重试');
    }
  }

  void login() async {
    //1.手机号和验证码 不能为空
    if (phoneController.text.isEmpty || codeController.text.isEmpty) {
      PromptAction.showToast('请输入手机号或验证码');
      return;
    }
    //2.手机号和验证码 必须是正确的
    if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(phoneController.text) ||
        !RegExp(r'^\d{6}$').hasMatch(codeController.text)) {
      PromptAction.showToast('请输入正确的手机号或验证码');
      return;
    }
    final res = await loginApi({
      "mobile": phoneController.text,
      "code": codeController.text,
    });

    await tokenManager.setToken(res['token'],
        refreshToekn: res['refresh_token']);
    emitter.fire(LogSuccessEvent());
    PromptAction.showToast('登录成功');
    if (widget.toName != null) {
      Navigator.pushNamed(context, widget.toName!);
      return;
    }
    Navigator.pop(context); //返回上一个页面
  }

  @override
  void dispose() {
    super.dispose();
    timer?.cancel();
  }

//声明一个Controller 绑定手机号
  TextEditingController phoneController = TextEditingController();
  //声明一个Controller 绑定验证码
  TextEditingController codeController = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('登录'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: Container(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const Row(
              children: [
                Text(
                  '登录',
                  style: TextStyle(
                    fontSize: 25,
                    fontWeight: FontWeight.bold,
                  ),
                )
              ],
            ),
            const SizedBox(height: 10),
            const Row(
              children: [
                Text(
                  '加入享+, 让生活更轻松',
                  style: TextStyle(fontSize: 15),
                )
              ],
            ),
            const SizedBox(height: 30),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Expanded(
                  child: TextField(
                    controller: phoneController,
                    decoration: const InputDecoration(
                      labelText: '手机号',
                      hintText: '请输入手机号',
                    ),
                  ),
                ),
                ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    shadowColor: Colors.transparent,
                    foregroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    //
                    beginCount();
                  },
                  child: Text(
                    seconds == 0 ? '重新获取' : '获取验证码($seconds)',
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            Expanded(
              child: TextField(
                controller: codeController,
                decoration: const InputDecoration(
                  labelText: '验证码',
                  hintText: '请输入6位验证码',
                ),
              ),
            ),
            const SizedBox(height: 8),
            const Row(
              children: [
                Text(
                  '未注册手机号经验证后将自动登录',
                  style: TextStyle(fontSize: 12, color: Colors.grey),
                ),
              ],
            ),
            const SizedBox(height: 50),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      login();
                    },
                    child: const Text(
                      '登录',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20,
                      ),
                    ),
                  ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}
